
package com.ljfiction.book.tools;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.widget.RemoteViews;
import android.widget.Toast;


import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.ljfiction.book.R;

import java.io.File;


public class DownLoadService extends Service {
    private final int REQUEST_STORAGE_PERMISSION = 11;
    private File result;


    public DownLoadService() {

    }

    @Override
    public IBinder onBind(Intent intent) {

        throw new UnsupportedOperationException("Not yet implemented");
    }

    public PendingIntent getDefalutIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }

    int a = 0;
    private Notification notification;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       /* String downPath = intent.getStringExtra("downloadURL");//xiaz.apk;//下载路径 根据服务器返回的apk存放路径
        showDownloadDialog(downPath);*/
        final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        RemoteViews view = new RemoteViews(getPackageName(), R.layout.notift_item);
            notification = new NotificationCompat.Builder(this,"辣鸡小说").setContent(view)
                .setTicker("正在下载辣鸡小说") //通知首次出现在通知栏，带上升动画效果的
                .setOngoing(true)//设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐) 或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setSmallIcon(R.mipmap.ic_launcher)//设置通知小ICON
                .setContentTitle("下载中")//设置通知栏标题
                .setContentText("正在下载请稍等")//设置通知栏显示内容
                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))//设置通知栏点击意图
                .build();




        HttpUtils httpUtils = new HttpUtils();
        httpUtils.download(intent.getStringExtra("downloadURL"), Environment.getExternalStorageDirectory()
                        + "/app-lajixs.apk",
                new RequestCallBack<File>() {

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        manager.cancel(112);
                        result = responseInfo.result;
                        int checkSelfPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);

                        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    REQUEST_STORAGE_PERMISSION);
                        } else {
                            Intent intent2 = new Intent(Intent.ACTION_VIEW);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent2.setAction("android.intent.action.VIEW");
                                intent2.addCategory("android.intent.category.DEFAULT");
                                intent2.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.ljfiction.book.fileprovider", responseInfo.result);
                                intent2.setDataAndType(contentUri, "application/vnd.android.package-archive");
                            } else {
                                intent2.setAction("android.intent.action.VIEW");
                                intent2.addCategory("android.intent.category.DEFAULT");
                                intent2.setDataAndType(Uri.fromFile(responseInfo.result), "application/vnd.android.package-archive");
                                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }

                            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent2, 0);

                            getApplicationContext().startActivity(intent2);

                            notification = new NotificationCompat.Builder(DownLoadService.this,"辣鸡小说")
                                    .setTicker("下载完毕") //通知首次出现在通知栏，带上升动画效果的
                                    .setOngoing(true)//设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐) 或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                                    .setSmallIcon(R.mipmap.ic_launcher)//设置通知小ICON
                                    .setContentTitle("辣鸡小说下载完毕")//设置通知栏标题
                                    .setContentText("点击安装")//设置通知栏显示内容
                                    .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))//设置通知栏点击意图
                                    .setContentIntent(pendingIntent)//跳到指定页
                                    .setAutoCancel(true)
                                    .build();

                            manager.notify(113, notification);


//                            RemoteViews contentView = notification.contentView;
//                            contentView.setTextViewText(R.id.tv,"正在安装");
//                            manager.notify(112, notification);
//                            //有权限了
                            //下载完成后自动安装
                            //installApp(responseInfo.result);
                        }


                    }

                    public void onLoading(long total, long current, boolean isUploading) {


                        RemoteViews contentView = notification.contentView;
                        contentView.setTextViewText(R.id.notification_tv, (int) (((double) current / (double) total) * 100) + "%");
//                contentView.setProgressBar(R.id.progress, 100, rate, false);
                        contentView.setProgressBar(R.id.notification_pb, 100, (int) (((double) current / (double) total) * 100), false);
                        manager.notify(112, notification);
                    }

                    @Override
                    public void onFailure(HttpException error,
                                          String msg) {
                    }
                });
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 显示软件下载对话框
     */
    private long downloadId;
    private  DownloadManager  mDownloadManager;
    private void showDownloadDialog(String downPath) {


        //使用系统下载类
       mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(downPath);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setAllowedOverRoaming(false);

        //创建目录下载
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "lajixs.apk");
        // 把id保存好，在接收者里面要用
        downloadId = mDownloadManager.enqueue(request);
        //设置允许使用的网络类型，这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //机型适配
        request.setMimeType("application/vnd.android.package-archive");
        //通知栏显示
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("下载");

        request.setDescription("正在下载中...");
        request.setVisibleInDownloadsUi(true);
        registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }



    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };


    /**
     * 检查下载状态
     */
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    installAPK();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        cursor.close();
    }

    /**
     * 7.0兼容
     */
    private void installAPK() {
        File apkFile =
                new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "下载.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
      startActivity(intent);
    }

    private void installApp(File t) {

        /*Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(t),
                "application/vnd.android.package-archive");
        startActivity(intent);*/

      /*  File apkFile =
                new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "下载.apk");*/
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", t);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive");
        }
        startActivity(intent);

    }
}